﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;

namespace AQMProject
{
    class YahooCsvLoader
    {
        private static readonly string CSV_COMMENT = "#";
        private static readonly char CSV_SEPERATOR = ',';
        private static readonly string DECIMAL_SEPERATOR = ".";

        public static List<ShareData> readYahhoCsvFromWeb(Uri url)
        {
            HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;
            using (StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream()))
            {
                var query =
                    from line in reader.Lines().Skip(1)
                    let items = line.Split(CSV_SEPERATOR)
                    where !line.StartsWith(CSV_COMMENT)
                    select new ShareData
                    {
                        Date = Convert.ToDateTime(items[0]),
                        Open = converToFloat(items[1]),
                        High = converToFloat(items[2]),
                        Low = converToFloat(items[3]),
                        Close = converToFloat(items[4]),
                        Volume = converToFloat(items[5]),
                        AdjustedClose = converToFloat(items[6])
                    }
                ;
                return query.OrderBy(n => n.Date).ToList();
            }
        }

        private static float converToFloat(string value)
        {
            return (float)Convert.ToDouble(value.Replace(DECIMAL_SEPERATOR, ","));
        }
    }
}
